package com.topisv.tms.web.base;

import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.data.domain.Page;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.utils.TopUtils;
import com.topisv.tms.utils.enums.DataTableEnums;

public class BaseDataTableController extends BaseController{
	
	/**
	 * 将查询结果封装为dataTable识别的json对象
	 * @param page
	 * @return JSONObject
	 */
	public <T> JSONObject bulidJSON(Page<T> page) {
		JSONObject json = new JSONObject();
		json.put(DataTableEnums.AA_DATA.getValue(), page.getContent());
		json.put(DataTableEnums.TOTAL_RECORED.getValue(), page.getTotalElements());
		json.put(DataTableEnums.TOTAL_RECORED_DISPLAY.getValue(), page.getTotalElements());
		return json;
	}
	
	/**
	 * 收集以特定字符串开头的查询条件,并得到分页的条件
	 * @param paramJson
	 * @param prefix
	 * @return QueryParamHolder
	 */
	public QueryParamHolder collectParam(JSONParam[] paramJson,String prefix){
		// 客户端参数
		Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
		int start = Integer.parseInt(paramMap.get(DataTableEnums.DISPLAY_START.getValue()));
		int pageSize = Integer.parseInt(paramMap.get(DataTableEnums.DISPLAY_LENGTH.getValue()));
		// 查询
		int curPage = (start / pageSize) + 1;
		Map<String, Object> searchParams = DataTablesUtils.getParametersStartingWith(paramMap, prefix);
		return new QueryParamHolder(start, pageSize, curPage, paramMap, TopUtils.cleanupMap2(searchParams));
	}
	/**
	 * 默认以search_开头收集
	 * @param paramJson
	 * @return QueryParamHolder
	 */
	public QueryParamHolder collectParam(JSONParam[] paramJson){
		return collectParam(paramJson, "search_");
	}
	
	/**
	 * 默认以 ' _ ' 开头收集
	 * 
	 * @param 
	 * @return 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
	public QueryParamHolder collectParamNew(JSONParam[] paramJson){
        return collectParam(paramJson, "_");
    }
}
